#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    defaultTextFormat=ui->display->currentCharFormat();
    say(QStringLiteral("你好，")  + user.name + QStringLiteral("，我是您的AI助理，在此为您服务"));
    db=sp_createLocalStorage();
    if(!db_try())
        append(QStringLiteral("无法连接到数据库，无法使用本地命令"));
    else
    {
        cmdStore.connectStorage(db,TD_REF_CMD);
        bookmarks.connectStorage(db,TD_BOOKMARKS);
    }
}

Widget::~Widget()
{
    if(db.isOpen())
        db.close();
    delete ui;
}

bool Widget::db_try()
{
    if(!db.isOpen())
    {
        return db.open();
    }
    else
        return true;
}

void Widget::say(const QString &word)
{
    ui->display->append(word);
}

void Widget::append(const QString &word)
{
    ui->display->append(word);
}

void Widget::clear()
{
    ui->display->clear();
    ui->display->setCurrentCharFormat(defaultTextFormat);
    say(QStringLiteral("你好，")  + user.name + QStringLiteral("，我是您的AI助理，在此为您服务"));
}

void Widget::onReceivedObject(const QJsonObject &object)
{
    Q_UNUSED(object)
}

void Widget::on_btn_submit_clicked()
{
    input_=ui->input->text().trimmed();
    if(input_.isEmpty())
        return;

    if(!cmdStore.isEmpty())
    {
        int code=cmdStore.parseCommand(input_);
        if(code != CMD_NULL)
            executeCommand(code);
        else
            say("暂时不清楚T_T");
    }
    else
        say("暂时不清楚T_T");

    ui->display->setCurrentCharFormat(defaultTextFormat);
    ui->display->append(QStringLiteral("我：") + input_);
    ui->input->clear();
}

void Widget::executeCommand(int code)
{
    switch (code) {
    case CMD_ACTION_EXIT:
        qApp->quit();
        break;
    case CMD_ACTION_SEARCH:
    {
        if(cmdStore.getArgs().isEmpty())
            return;

        QString url=P_SEARCH +cmdStore.getArgs().first();
        QDesktopServices::openUrl(QUrl(url));
    }
        break;
    case CMD_BAIDU:
    {
        if(cmdStore.getArgs().isEmpty())
            return;

        QString url=P_SEARCH +cmdStore.getArgs().first();
        QDesktopServices::openUrl(QUrl(url));
    }
        break;
    case CMD_TAOBAO:
    {
        if(cmdStore.getArgs().isEmpty())
            return;

        QString url=P_TAOBAO +cmdStore.getArgs().first();
        QDesktopServices::openUrl(QUrl(url));
    }
        break;
    case CMD_ACTION_OPEN:
    {
        if(cmdStore.getArgs().isEmpty())
            return;

        QString label=cmdStore.getArgs().first();
        bookmarks.open(label);
    }
        break;
    }
}
